/**
 * 定义检查权限中间件
 */

module.exports ={
  //检查用户登录状态
  isLogin : function(req,res,next){
   let session = req.session.user
   if(!session){
     req.flash('error')
     req.flash('error','登录信息失效，请重新登录')
     return res.redirect('/admin/login')
   }
   next();
  },
  //检查验证码
  checkCapt:function(req,res,next){
    let capt = req.body.capt.toLowerCase()
    let scapt = req.session.captcha.toLowerCase()
    if(capt!=scapt){
      req.flash('error')
      req.flash('error','验证码错误')
      return res.redirect('/admin/login')
    }
    next();
  },
  //检查权限
  isPower1:function(req,res,next){
    let user = req.session.user
    if(user.level>=1){
      req.flash('msg')
      req.flash('msg','sorry，权限不足，请联系管理员')
     return res.redirect('/admin/noPower')
    }
    next()
  },
  isPower2:function(req,res,next){
    let user = req.session.user
    if(user.level>=2){
      req.flash('msg')
      req.flash('msg','sorry，权限不足，请联系管理员')
     return res.redirect('/admin/noPower')
    }
    next()
  },
  isLogined: function(req,res,next){
    let session = req.session.user
   if(session){
     return res.redirect('/admin')
   }
   next();
  },
  canTop:function(req,res,next){
    let user = req.session.user
    let body = req.body
    if(user.level>=2){
      if(body.top!= undefined ||body.good !=undefined){
        req.flash('msg')
        req.flash('msg','您没有权限对文章进行置顶或精华操作')
        return res.redirect('/admin/noPower')
      }
    }
    next()
  },
  passCmts:function(req,res,next){
    let user = req.session.user
    if(!user){
      return res.json({code:0,msg:'登录失效，请刷新重新登录'})
    }else{
      if(user.level>=2){
        return res.json({code:-1,msg:'没有权限审核或删除评论'})
      }
    }
    next()
  }

}